import datetime

from webapp.extensions import AppException
from webapp.models import Grade, db


class GradeService:
    @staticmethod
    def query_all(page=0, size=9999, **kwargs) -> list:
        create_times = kwargs.get('createTime')
        classname = kwargs.get('classname')
        not_empty = classname or create_times
        query = []
        if classname:
            query.append((Grade.classname.like(f'%{classname}%')))
        if create_times and len(create_times) >= 2:
            query.append((Grade.create_time.between(create_times[0], create_times[1])))
        result = Grade.query.filter(*query).paginate(int(page) + 1, per_page=int(size),
                                                     error_out=False)
        return result

    @staticmethod
    def find_by_id(id):
        grade = db.session.query(Grade).filter(Grade.id == id).one_or_none()
        if grade is None:
            raise AppException(f'您所操作的对象已不存在!')
        return grade

    @staticmethod
    def delete(grade_set):
        if grade_set:
            for grade in grade_set:
                db.session.delete(grade)
            db.session.commit()

    @staticmethod
    def create(curr_grade: Grade):
        grade = Grade.query.filter(Grade.classname == curr_grade.classname).one_or_none()
        if grade:
            raise AppException(f'{curr_grade.name}已存在!')
        curr_grade.create_time = datetime.datetime.now()
        db.session.add(curr_grade)
        db.session.commit()

    @staticmethod
    def update(curr_grade: Grade):
        grade = Grade.query.filter(Grade.id == curr_grade.id).one_or_none()
        if grade is None:
            raise AppException(f'修改的数据可能已不存在!')
        grade.majorname = curr_grade.majorname
        grade.majorcode = curr_grade.majorcode
        grade.classname = curr_grade.classname
        grade.classnum = curr_grade.classnum
        grade.classid = curr_grade.classid
        grade.studyweek = curr_grade.studyweek
        grade.update_time = datetime.datetime.now()
        grade.update_by = curr_grade.update_by
        db.session.commit()

    @staticmethod
    def updateStudyWeek(id, update_by, studyweek):
        grade = Grade.query.filter(Grade.id == id).one_or_none()
        grade.studyweek = studyweek
        grade.update_time = datetime.datetime.now()
        grade.update_by = update_by
        db.session.commit()
